package com.red.star.wechat.data.repository;

import com.red.star.wechat.data.core.constant.MongoConstant;
import com.red.star.wechat.data.entity.ChatRequest;
import com.red.star.wechat.data.entity.ChatRequestItem;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author nofish.yan@gmail.com
 * @date 2018/2/9.
 * 用户发起聊天请求记录
 */
@Repository
public class ChatRequestRepository {

    @Resource
    private MongoTemplate mongoTemplate;

    public ChatRequest findChatRequestByFansId(Integer cFansId) {
        Query query = Query.query(Criteria.where("c_fans_id").is(cFansId));
        return mongoTemplate.findOne(query, ChatRequest.class, MongoConstant.COLLECTION_NAME_OF_CHAT_REQUEST);
    }

    public ChatRequest findAdminChatRequestByFansId(Integer adminId) {
        Query query = Query.query(Criteria.where("admin_id").is(adminId));
        return mongoTemplate.findOne(query, ChatRequest.class, MongoConstant.COLLECTION_NAME_OF_CHAT_REQUEST);
    }

    public int saveChatRequest(Integer cFansId, ChatRequestItem request) {
        Query query = Query.query(Criteria.where("c_fans_id").is(cFansId));
        Update update = Update.update("update_time", new Date()).push("requests", request);
        int n = mongoTemplate.upsert(query, update, ChatRequest.class, MongoConstant.COLLECTION_NAME_OF_CHAT_REQUEST).getN();
        return n;
    }

    public int saveAdminChatRequest(Integer adminId, ChatRequestItem request) {
        Query query = Query.query(Criteria.where("admin_id").is(adminId));
        Update update = Update.update("update_time", new Date()).push("requests", request);
        int n = mongoTemplate.upsert(query, update, ChatRequest.class, MongoConstant.COLLECTION_NAME_OF_CHAT_REQUEST).getN();
        return n;
    }

}
